<?php

namespace app\admin\controller\service\shop;

use app\common\controller\Backend;
use think\Db;

/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\service\shop\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\shop\Goods;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("toShopList", $this->model->getToShopList());
        $this->view->assign("isTravelList", $this->model->getIsTravelList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("chooseSkillTypeList", $this->model->getChooseSkillTypeList());
        $this->view->assign("shopStateList", $this->model->getShopStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('shop_id','>',0)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$value)
        {
            $value->shopname = \app\admin\model\service\shop\Shop::where('id',$value->shop_id)->value('name');
            $value->categoryName = \app\admin\model\service\Category::where('id',$value->category_id)->value('name');
            $value->twoCategoryName = \app\admin\model\service\Category::where('id',$value->two_category_id)->value('name');
            $value->skillCateName = \app\api\model\service\SkillCate::getNameList($value->skill_cate_ids);
            $value->update_time = $value->updatetime?date("Y-m-d",$value->updatetime):'';
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    public function edit($ids = null){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $spu = \app\admin\model\service\Goodsspu::where(['goods_id'=>$row->id,'status'=>'normal'])->field('name,skudetail')->select();
            foreach ($spu as &$item){
                $info = explode(',',$item['skudetail']);
                $arr=[];
                foreach ($info as $val){
                    $v['name'] = $val;
                    array_push($arr,$v);
                }
                $item['info'] = $arr;
            }
            $row->city = $row->province.'/'.$row->city;
            $sku = \app\admin\model\service\Goodssku::where(['goods_id'=>$row->id,'status'=>'normal'])->field('name,price,cost_seconds')->select();
            $this->assignconfig('spu',$spu);
            $this->assignconfig('sku',$sku);
            $this->assignconfig('spec_type',$row['spec_type']);
            $this->assignconfig('choose_skill_type',$row['choose_skill_type']);
            $this->assignconfig('status',$row['status']);
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $result = false;
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            //$params['district'] = isset($address[1])?:'';
        }else{
            unset($params['city']);
        }
        Db::startTrans();
        try {
            $goods = new \app\admin\model\service\shop\Goods ();
            
            $goods->allowField(true)->save($params,['id'=>$row->id]);
            $result = true;
            if($params['status'] == 'normal')
            {
                if($params['spec_type'] == 1)
                {
                    \app\admin\model\service\Goodsspu::where(['goods_id'=>$row->id,'status'=>'normal'])->update(['status'=>'hidden']);
                    \app\admin\model\service\Goodssku::where(['goods_id'=>$row->id,'status'=>'normal'])->update(['status'=>'hidden']);
                    $spuList = json_decode($params['spu'],true);

                    $spu = [];

                    foreach ($spuList as $value) {

                        $spu[] = [
                            'goods_id'	=> $row->id,
                            'name'		=> $value['name'],
                            'skudetail'=> implode(',',array_column($value['info'],'name'))
                        ];
                    }

                    if(!model('\app\admin\model\service\Goodsspu')->allowField(true)->saveAll($spu)){
                        $result == false;
                    }

                    $skuList = json_decode($params['sku'],true);
                    $sku = [];
                    foreach ($skuList  as $value) {

                        $sku[] = [
                            'goods_id' 		=> $row->id,
                            'name' 	        => $value['name'],
                            'price' 		=> $value['price'],
                        ];
                    }
                    if(!model('\app\admin\model\service\Goodssku')->allowField(true)->saveAll($sku)){
                        $result == false;
                    }
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function agree($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        $row->shop_state != 0 && $this->error('请勿重复审核');
        \app\admin\model\service\shop\Goods::where('id',$ids)->update(['shop_state'=>1]);
        $shopGoodsIds = \app\admin\model\service\shop\Shop::where('id',$row->shop_id)->value('goods_ids');
        $shopGoodsArr = explode(',',$shopGoodsIds);
        if(!in_array($ids,$shopGoodsArr))
        {
            \app\admin\model\service\shop\Shop::where('id',$row->shop_id)->update(['goods_ids'=>$row->id.','.$shopGoodsIds]);
        }
        $this->success('商品审核已通过');

    }

    public function refuse($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        $row->shop_state != 0 && $this->error('请勿重复审核');
        if ($this->request->isPost())
        {
            $params = $this->request->post('row/a');
            \app\admin\model\service\shop\Goods::where('id',$ids)->update(['note'=>$params['note'],'shop_state'=>-1]);
            $this->success('审核拒绝');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }





}
